<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-select
          v-model="pageParam.state"
          clearable
          placeholder="请选择状态 "
        >
          <el-option label="待发布" :value="0"></el-option>
          <el-option label="发布" :value="1"></el-option>
          <el-option label="下架" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList('reset')">查询</el-button>
        <el-button type="primary" @click="openDetails('save')">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="pageList"
      border
      v-loading="pageListLoading"
      style="width: 100%"
      stripe
      border
      :header-cell-style="{
        background: '#eef1f6',
        color: '#606266',
        height: '70px'
      }"
    >
      <el-table-column
        header-align="center"
        align="center"
        width="80"
        label="序号"
      >
        <template slot-scope="scope">
          <span>{{
            scope.$index + (pageParam.page - 1) * pageParam.limit + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="title"
        show-overflow-tooltip
        header-align="center"
        align="center"
        label="标题"
      ></el-table-column>
      <el-table-column
        prop="type"
        header-align="center"
        align="center"
        width="140"
        label="文件类型"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.type == 0">图片</div>
          <div v-if="scope.row.type == 1">视频</div>
          <div v-if="scope.row.type == 2">音频</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="filePath"
        header-align="center"
        align="center"
        label="文件路径"
      ></el-table-column>
      <el-table-column
        prop="detail"
        show-overflow-tooltip
        header-align="center"
        align="center"
        label="详情"
      ></el-table-column>
      <el-table-column
        prop="state"
        header-align="center"
        align="center"
        width="100"
        label="状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state == 0">待发布</el-tag>
          <el-tag v-if="scope.row.state == 1" type="success">发布</el-tag>
          <el-tag v-if="scope.row.state == 2" type="warning">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="openDetails('show', scope.row)"
            class="c-info"
            >查看</el-button
          >
          <el-button
            v-if="scope.row.state == 0 || scope.row.state == 2"
            type="text"
            size="small"
            @click="switchCheck(scope.row)"
            >发布</el-button
          >
          <el-button
            v-if="scope.row.state == 1"
            type="text"
            size="small"
            @click="switchCheck(scope.row)"
            class="c-info"
            >下架</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="openDetails('update', scope.row)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="delData(scope.row)"
            class="c-error"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="sizeChange"
      @current-change="pageChange"
      :current-page="pageParam.page"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageParam.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    ></el-pagination>
    <el-dialog
      v-loading="loading"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        ref="form"
        :disabled="dialogTitle == '查看'"
        :rules="rules"
        :model="fromData"
        label-width="140px"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            maxlength="50"
            v-model="fromData.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件类型" prop="type">
          <el-select
            @change="typeChange"
            v-model="fromData.type"
            placeholder="请选择"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="文件路径"
          prop="file_path"
          v-if="typeof fromData.type == 'number'"
        >
          <div>
            <el-popover
              v-if="fromData.type == 0 && fromData.file_path"
              placement="top-start"
              trigger="click"
            >
              <a
                :href="fromData.file_path"
                target="_blank"
                title="查看最大化图片"
                ><img
                  :src="fromData.file_path"
                  style="width: 300px;height: 300px"
              /></a>
              <img
                slot="reference"
                @click="$openImg(fromData.file_path)"
                :src="fromData.file_path"
                style="width: 100px;height: 100px; cursor:pointer"
              />
            </el-popover>
            <video
              v-if="fromData.type == 1 && fromData.file_path"
              :src="fromData.file_path"
              class="avatar"
              controls="controls"
            ></video>
            <audio
              v-if="fromData.type == 0 && fromData.file_path"
              :src="fromData.file_path"
            ></audio>
            <!-- <upload :uploadType="uploadType" @getUpload="getUpload" :isStop='fromData.file_path?true:false' :editorArr='editorArr'></upload> -->

            <el-upload
              :accept="file_type"
              class="upload-demo"
              :action="$config.upload_url"
              :http-request="beforeUploadHandle"
              :on-success="fileSuccess"
              :on-remove="handleRemove"
              name="file"
              :limit="1"
              :file-list="fileList"
            >
              <el-button size="small" v-if="!fromData.file_path" type="primary"
                >点击上传</el-button
              >
              <el-button size="small" v-else type="primary" @click.stop="stop"
                >移除</el-button
              >
              <!-- <el-button size="small" v-else type="primary"  >点击上传</el-button> -->
            </el-upload>

            <el-input
              type="textarea"
              class="mt10"
              @input="onInput"
              v-model="fromData.file_path"
              placeholder="请输入文件路径"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="详情" prop="detail">
          <el-input
            type="textarea"
            maxlength="255"
            v-model="fromData.detail"
            placeholder="请输入详情"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="修改时间"
          prop="detail"
          v-if="dialogTitle == '查看'"
        >
          <el-input v-model="fromData.updateTime"></el-input>
        </el-form-item>
        <el-form-item
          label="创建时间"
          prop="detail"
          v-if="dialogTitle == '查看'"
        >
          <el-input v-model="fromData.createTime"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          v-if="dialogTitle == '新增'"
          type="primary"
          :loading="btnLoading"
          @click="saveDateils"
          >确 定</el-button
        >
        <el-button
          v-if="dialogTitle == '修改'"
          type="primary"
          :loading="btnLoading"
          @click="updateDateils"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import merchantApi from '@/api/merchantService.js'
// import upload from '@/components/upload/upload.vue'
import axios from 'axios'
import Vue from 'vue'
export default {
  components: {
    // upload
  },
  data() {
    return {
      loading: false,
      isStop: false,
      fileList: [],
      pageParam: {
        page: 1,
        limit: 10
      },
      totalCount: 0,
      pageList: [],
      dialogVisible: false,
      pageListLoading: false,
      btnLoading: false,
      dialogTitle: '详情', // 详情弹窗 title
      rules: {
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }
        ],
        file_path: [
          {
            required: true,
            message: '请输入文件路径',
            trigger: 'blur'
          }
        ],
        type: [
          {
            required: true,
            message: '请选择文件类型 ',
            trigger: 'blur'
          }
        ],
        detail: [
          {
            required: true,
            message: '请输入详情 ',
            trigger: 'blur'
          }
        ]
      },
      fromData: {},
      file_type: '.mp3',
      typeOptions: [
        {
          label: '图片',
          value: 0
        },
        {
          label: '视频',
          value: 1
        },
        {
          label: '音频',
          value: 2
        }
      ],
      uploadType: 'img'
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    onInput() {
      this.$forceUpdate()
    },
    stop() {
      this.fromData.file_path = ''
      this.fileList = []
      console.log('stop')
    },
    fileSuccess(file, e) {
      this.$forceUpdate()
    },
    handleRemove(file, fileList) {
      this.fromData.file_path = ''
      this.fileList = []
    },
    beforeUploadHandle(file) {
      console.log(file)
      // 图片
      const isJPG = file.file.type === 'image/jpeg'
      const isPNG = file.file.type === 'image/png'
      const isGif = file.file.type === 'image/gif'

      // 视频
      const isMP4 = file.file.type === 'video/mp4'
      const isFlv = file.file.type === 'video/flv'
      const isAvi = file.file.type === 'video/avi'
      const isWMV = file.file.type === 'video/wmv'

      // 音频
      const isMP3 = file.file.type === 'audio/mpeg'
      const isFlc = file.file.type === 'audio/flc'

      const isLt5M = file.file.size / 1024 / 1024 < 5
      const isLt10M = file.file.size / 1024 / 1024 < 10
      const isLt20M = file.file.size / 1024 / 1024 < 20
      if (this.uploadType == 'img') {
        if (!isJPG && !isPNG) {
          this.$message.error('上传图片只能是 JPG /png/Gif格式!')
          this.fileList = []
          return
        }
        if (!isLt5M) {
          this.$message.error('上传图片大小不能超过 5MB!')
          this.fileList = []
          return
        }
        // return (isJPG || isPNG || isGif) && isLt5M;
      } else if (this.uploadType == 'video') {
        // 视频文件
        if (!isMP4 && !isFlv && !isAvi) {
          this.$message.error('请上传视频文件')
          this.fileList = []
          return
        }
        if (!isLt20M) {
          this.$message.error('上传图片大小不能超过 20MB!')
          this.fileList = []
          return
        }
        // return (isMP4 || isFlv || isAvi) && isLt20M
      } else {
        // 音频文件
        if (!isMP3 && !isFlc) {
          this.$message.error('请上传音频的文件')
          this.fileList = []
          return
        }
        if (!isLt10M) {
          this.$message.error('上传图片大小不能超过 10MB!')
          this.fileList = []
          return
        }
        // return (isMP3  || isFlc) && isLt10M
      }
      console.log(111111)
      this.requestHttp(file)
    },
    random_string(len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    requestHttp(file) {
      this.loading = true
      let formData = new FormData()
      formData.append('file', file.file)
      let config = {
        headers: {
          token: Vue.cookie.get('token'),
          'Content-Type': 'multipart/form-data'
        }
      }
      axios
        .post(
          `${this.$config.SERVER_URL}/admin/sys/oss/upload`,
          formData,
          config
        )
        .then(obj => {
          if (obj.status == 200) {
            this.fromData.file_path = obj.data.data.url
          }
          this.loading = false
        })
    },
    // 获取列表
    getDataList(reset) {
      let that = this
      if (reset) {
        this.pageParam.page = 1
      }
      for (let v in this.pageParam) {
        if (this.pageParam[v] === '') {
          this.pageParam[v] = null
        }
      }
      this.pageListLoading = true
      merchantApi.materialPage(this.pageParam).then(res => {
        if (res.data && res.data.code === 200) {
          this.pageList = res.data.page.list
          this.totalCount = res.data.page.totalCount
        }
        that.pageListLoading = false
      })
    },
    // 类型 change事件
    typeChange(e) {
      this.fromData.file_path = ''
      this.fileList = []

      if (e == 0) {
        this.uploadType = 'img'
        this.file_type = '.jpg,.jpeg,.png'
      } else if (e == 1) {
        this.uploadType = 'video'
        this.file_type = '.mp4,.avi,.flv'
      } else {
        this.uploadType = 'audio'
        this.file_type = '.mp3,.flc'
      }
    },
    // 获取上传的文件
    getUpload(e) {
      this.fromData.file_path = e[0]
      this.$forceUpdate()
    },
    // 发布或上架
    switchCheck(row) {
      let param = {
        id: row.id
      }
      if (row.state == 0 || row.state == 2) {
        param.state = 1
      } else {
        param.state = 2
      }
      merchantApi.materialCheck(param).then(res => {
        if (res.data && res.data.code == 200) {
          this.$message.success('操作成功')
          this.getDataList()
        }
      })
    },
    // 删除
    delData(row) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.pageListLoading = true
          merchantApi.materialDel(row.id).then(res => {
            this.pageListLoading = false
            if (res.data && res.data.code == 200) {
              this.$message.success('删除成功')
              this.getDataList()
            }
          })
        })
        .catch(() => {})
    },
    // 新增
    saveDateils() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.btnLoading = true
          merchantApi.materialSave(this.fromData).then(res => {
            if (res.data && res.data.code == 200) {
              this.$message.success('提交成功')
              this.handleClose()
              this.getDataList()
            }
            this.btnLoading = false
          })
        }
      })
    },
    // 编辑
    updateDateils() {
      this.$refs.form.validate(valid => {
        this.btnLoading = true
        merchantApi.materialUpdate(this.fromData).then(res => {
          if (res.data && res.data.code == 200) {
            this.$message.success('提交成功')
            this.handleClose()
            this.getDataList()
          }
          this.btnLoading = false
        })
      })
    },
    // 获取详情
    getDeatils(row) {
      merchantApi.materialInfo(row.id).then(res => {
        if (res.data && res.data.code == 200) {
          this.fromData = res.data.data
          this.fromData.file_path = res.data.data.filePath
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },
    // 打开弹窗
    openDetails(val, row) {
      if (val == 'show') {
        this.typeChange(row.type)
        this.dialogTitle = '查看'
        this.fromData = { ...row }
        this.fromData.file_path = row.filePath

        // this.getDeatils(row)
      } else if (val == 'update') {
        this.typeChange(row.type)
        this.fromData = { ...row }
        this.fromData.file_path = row.filePath
        this.dialogTitle = '修改'
        // this.getDeatils(row)
      } else if (val == 'save') {
        this.dialogTitle = '新增'
        // this.fromData.id = ''
        // this.fromData.type = ''
        // this.fromData.file_path = ''
        // this.fromData.title = ''
        // this.fromData.detail = ''
      }
      this.dialogVisible = true
    },
    // 每页数
    sizeChange(val) {
      this.pageParam.limit = val
      this.pageParam.page = 1
      this.getDataList()
    },
    // 当前页
    pageChange(val) {
      this.pageParam.page = val
      this.getDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
.flex {
  display: flex;
}
</style>
